<?php
namespace app\admin\controller;
use \app\admin\controller\Base;
class Menu extends Base{
	public function menu_list(){
		$menus = db('AdminMenu')->select();//查找数据库 返回array
		$menu_arr_list = array();
		//获取第一级菜单
		foreach ($menus as $m) {
			if ($m['p_id']==0){
				$menu_arr_list[] = $m;
			}
		}
		//获取二级菜单
		foreach ($menu_arr_list as $k=>$m_arr){
			foreach ($menus as $m) {
				if ($m['p_id']==$m_arr['id']){
					$menu_arr_list[$k]['sub_menu'][] = $m;
				}
			}
		}
		$this->assign('menu_arr_list',$menu_arr_list);//向模板输出变量
		return $this->fetch();
	}
	//添加一级菜单
	public function menu_add(){
		if($this->request->isPost()){
			$requestArr=$this->request->param();
			$requestArr['sort'] = $requestArr['sort']?$requestArr['sort']:0;//排序
			$requestArr['p_id'] = 0;
			db('AdminMenu')->insert($requestArr);
			$this->success('添加一级菜单成功','Menu/menu_list');
			exit;
		}
		return $this->fetch();
	}
	//添加二级菜单
	public function sub_menu_add(){
		if($this->request->isPost()){
			$requestArr=$this->request->param();
			$requestArr['sort'] = $requestArr['sort']?$requestArr['sort']:0;//排序
			db('AdminMenu')->insert($requestArr);
			$this->success('添加二级菜单成功','Menu/menu_list');
			exit;
		}
		$menuArr=db('AdminMenu')->where('p_id=0')->select();
		$this->assign('menu_arr',$menuArr);
		return $this->fetch();
	}
	//修改菜单
	public function menu_edit(){
		$requestArr=$this->request->param();
		if($this->request->isPost()){
			db('AdminMenu')->update($requestArr);
			$this->success('修改成功','Menu/menu_list');
			exit;
		}
		$id = $requestArr['id'];
		$menu = db('AdminMenu')->where("id=$id")->find();
		$menus = db('AdminMenu')->select();
		$menu_arr = array();
		foreach ($menus as $m) {
			if ($m['p_id']==0){
				$menu_arr[] = $m;
			}
		}
		foreach ($menu_arr as $k=>$m_arr){
			foreach ($menus as $m) {
				if ($m['p_id']==$m_arr['id']){
					$menu_arr[$k]['sub_menu'][] = $m;
				}
			}
		}
		$this->assign('menu_1',$menu_arr);
		$this->assign('menu',$menu);
		return $this->fetch();
	}
	public function menu_delete(){
		$requestArr=$this->request->param();
		$id = $requestArr['id'];
		db('AdminMenu')->where("id=$id")->delete();
		//如果id是一级菜单 删除其下面的所有二级菜单
		db('AdminMenu')->where("p_id=$id")->delete();
		$this->success('删除成功','Menu/menu_list');
	}
}